<template>
    <div class="min-h-screen bg-gray-100 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
        <div class="sm:mx-auto sm:w-full sm:max-w-md">
            <h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900">
                欢迎使用GWDI智能助手
            </h2>
            <p class="mt-2 text-center text-sm text-gray-600">
                请登录或注册
            </p>
        </div>

        <div class="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
            <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
                <div class="flex space-x-4">
                    <button @click="isLogin = true"
                        :class="{ 'bg-blue-500 text-white': isLogin, 'bg-gray-200 text-gray-600': !isLogin }"
                        class="w-1/2 py-2 rounded-md">
                        登录
                    </button>
                    <button @click="isLogin = false"
                        :class="{ 'bg-blue-500 text-white': !isLogin, 'bg-gray-200 text-gray-600': isLogin }"
                        class="w-1/2 py-2 rounded-md">
                        注册
                    </button>
                </div>

                <form @submit.prevent="submitForm" class="mt-8 space-y-6">
                    <div>
                        <label for="username" class="text-left block text-sm font-medium text-gray-700">
                            用户名
                        </label>
                        <div class="mt-1">
                            <input id="username" v-model="formData.username" type="text" required placeholder="请输入用户名"
                                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" />
                        </div>
                    </div>

                    <div>
                        <label for="password" class="text-left block text-sm font-medium text-gray-700">
                            密码
                        </label>
                        <div class="mt-1">
                            <input id="password" v-model="formData.password" type="password" required
                                placeholder="请输入密码"
                                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" />
                        </div>
                    </div>

                    <div v-if="!isLogin">
                        <label class="text-left block text-sm font-medium text-gray-700">
                            性别
                        </label>
                        <div class="mt-1 flex space-x-20">
                            <div class="flex items-center">
                                <input id="male" type="radio" v-model="formData.sex" value="1" checked="checked"
                                    class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300" />
                                <label for="male" class="ml-2 block text-sm text-gray-900">
                                    男
                                </label>
                            </div>
                            <div class="flex items-center">
                                <input id="female" type="radio" v-model="formData.sex" value="0"
                                    class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300" />
                                <label for="female" class="ml-2 block text-sm text-gray-900">
                                    女
                                </label>
                            </div>
                        </div>
                    </div>

                    <div v-if="!isLogin">
                        <label for="email" class="text-left block text-sm font-medium text-gray-700">
                            邮箱
                        </label>
                        <div class="mt-1">
                            <input id="email" v-model="formData.email" type="email" required placeholder="请输入邮箱"
                                :class="{ 'border-red-500': emailError }" @blur="validateEmail"
                                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" />
                        </div>
                        <div v-if="emailError" class="text-red-500 text-sm mt-1">
                            请输入格式正确的邮箱
                        </div>
                    </div>

                    <div v-if="!isLogin">
                        <label for="verifiedCode" class="text-left block text-sm font-medium text-gray-700">
                            验证码
                        </label>
                        <div class="mt-1 flex">
                            <input id="verifiedCode" v-model="formData.verifiedCode" type="text" required
                                placeholder="请输入验证码"
                                class="mr-3 appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" />
                            <button :disabled="isDisabled" type="button"
                                class="bg-blue-500 text-white whitespace-nowrap py-2 px-4 rounded-md "
                                @click="getVerifiedCode">
                                {{ buttonText }}
                            </button>
                        </div>
                    </div>

                    <div>
                        <button type="submit"
                            class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-blue-500 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            <span class="absolute left-0 inset-y-0 flex items-center pl-3">
                                <i class="fa-solid fa-arrow-right"></i>
                            </span>
                            {{ isLogin ? '登录' : '注册' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useAdminInfoStore } from '../../store'
import { useAdminApi } from '../../api/admin'
import { useRouter } from 'vue-router';
// 登录和注册切换
const isLogin = ref(true);
// 邮件格式检车
const emailError = ref(false);
// 获取验证码间隔设置
const isDisabled = ref(false);
const countdown = ref(0);
const buttonText = ref('获取验证码');
// 实例化容器
const adminStore = useAdminInfoStore()
const adminApi = new useAdminApi()
const router = useRouter()
const formData = ref({
    username: '',
    email: '',
    password: '',
    sex: true,
    verifiedCode: '',
});
const adminLoginDTO = ref({
    username: '',
    password: '',
})
const adminRegisterDTO = ref({
    username: '',
    password: '',
    email: '',
    sex: '',
    verifiedCode: ''
})

// 验证邮箱格式否合法
const validateEmail = () => {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!emailRegex.test(formData.value.email)) {
        emailError.value = true;
    } else {
        emailError.value = false;
    }
};
// 获取验证码
const getVerifiedCode = () => {
    adminApi.getVerifiedCode(formData.value.email).then(response => {
        if (response.data.code == 1) {
            ElMessage({
                message: '验证码发送成功，请注意查收！',
                type: 'success',
            });
        } else {
            ElMessage.error(response.data.message)
        }
    }).catch(error => {
        console.error(error);
    })
    isDisabled.value = true;
    countdown.value = 60;
    buttonText.value = ` ${countdown.value} 秒`;

    const timer = setInterval(() => {
        countdown.value--;
        buttonText.value = ` ${countdown.value} 秒`;

        if (countdown.value === 0) {
            clearInterval(timer);
            isDisabled.value = false;
            buttonText.value = '获取验证码';
        }
    }, 1000);
};

const submitForm = () => {
    if (isLogin.value) {
        // 处理登录逻辑
        adminLoginDTO.value.username = formData.value.username;
        adminLoginDTO.value.password = formData.value.password;
        console.log('登录数据:', adminLoginDTO.value);
        adminApi.login(adminLoginDTO.value).then(response => {
            if (response.data.code == 1) {
                // 登录成功
                ElMessage({
                    message: '登录成功！',
                    type: 'success',
                });
                adminStore.setLoginStatus(true);
                adminStore.setToken(response.data.data.token);
                adminStore.setId(response.data.data.id);
                adminStore.setAvatar(response.data.data.avatar);
                adminStore.setSex(response.data.data.sex);
                adminStore.setRole(response.data.data.role);
                adminStore.setUsername(response.data.data.username);
                router.push('/home');
            } else {
                adminStore.setLoginStatus(false);
                ElMessage.error(response.data.message);
            }
        }).catch(error => {
            adminStore.setLoginStatus(false);
            console.error(error.message);
        });
    } else {
        // 处理注册逻辑
        adminRegisterDTO.value.username = formData.value.username;
        adminRegisterDTO.value.password = formData.value.password;
        adminRegisterDTO.value.sex = formData.value.sex == true ? 1 : 0;
        adminRegisterDTO.value.email = formData.value.email;
        adminRegisterDTO.value.verifiedCode = formData.value.verifiedCode;
        console.log('注册数据：', adminRegisterDTO.value);
        adminApi.register(adminRegisterDTO.value).then(response => {
            if (response.data.code == 1) {
                ElMessage({
                    message: '注册成功！',
                    type: 'success',
                });
                isLogin.value = true;
            } else {
                ElMessage.error(response.data.message)
            }
        }).catch(error => {
            console.error(error);
        });
    }
}
</script>

<style scoped></style>